package com.breeze.skinlib

import android.app.Activity
import android.app.Application
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.core.view.LayoutInflaterCompat
import java.lang.reflect.Field
import java.util.*

class MyActivityLifeCycleCallbacks(var observable: Observable) :
    Application.ActivityLifecycleCallbacks {
    private val TAG = "MyActivityLifeCycleCall"
    override fun onActivityPaused(activity: Activity) {
    }

    override fun onActivityStarted(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        // 该方法在Activity的onCreate中会被回调，setContentView执行在该方法后，故可以选择在该方法中设置Factory2
        Log.i(TAG, "onActivityCreated: ")
        var layoutInflater = activity.layoutInflater
        var skinLayoutInflaterFactory = SkinLayoutInflaterFactory()
        // 也可以在Android P以上通过命令关闭访问hidden api 限制 adb shell settings put global hidden_api_policy  1
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            try {
                //Android 布局加载器 使用 mFactorySet 标记是否设置过Factory
                //如设置过抛出异常
                //设置layoutInflater mFactorySet变量为false
                val field: Field = LayoutInflater::class.java.getDeclaredField("mFactorySet")
                field.isAccessible = true
                field.setBoolean(layoutInflater, false)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            // 设置自定义Factory2
            LayoutInflaterCompat.setFactory2(layoutInflater, skinLayoutInflaterFactory)
        } else {
            try {
                val field = LayoutInflater::class.java.getDeclaredField("mFactory2");
                field.isAccessible = true
                field.set(layoutInflater, skinLayoutInflaterFactory)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        observable.addObserver(skinLayoutInflaterFactory)
    }

    override fun onActivityResumed(activity: Activity) {
    }

    override fun onActivityStopped(activity: Activity) {
    }

    override fun onActivityDestroyed(activity: Activity) {

    }
}